const Router = require('koa-router')
const router = new Router({ prefix: '/cjwt' })
const u = require('../api')
var pageSize = 10

// 根目录
router.get('/', async (ctx) => {
  // 获取问题列表
  let getProblem = await u.http({
    url: u.queryQaList,
    params: {
      pageNum: 1,
      pageSize,
      title: ctx.query.keyword || ''
    }
  })
  // 获取新闻资讯列表
  let getNews = await u.http({
    url: u.queryNewsList,
    params: {
      pageNum: 1,
      pageSize: 15,
      newsType: ''
    }
  })
  // 面包屑
  let crumbsData = [{
    name: '首页',
    href: '/'
  }, {
    name: '常见问题',
    href: ''
  }]
  // 修改TDK
  ctx.config.tdk.title = `常见问题-彧胜实业`
  ctx.config.tdk.description = ''
  ctx.config.tdk.keywords = ''
  
  await ctx.render('cjwt.ejs', {
    config: ctx.config,
    problemData: getProblem.code == 200 ? getProblem.data.list : [],
    problemDataTotal: getProblem.code == 200 ? getProblem.data.total : 0,
    problemDataPageNum: getProblem.code == 200 ? getProblem.data.pageNum : 0,
    problemDataPageSize: pageSize,
    searchValue: ctx.query.keyword || '',
    newsData: getNews.code == 200 ? getNews.data.list : [],
    crumbsData
  })
})

// 二级目录
router.get('/p:page', async (ctx) => {
  // 验证分页
  if (!/^\d+$/.test(ctx.params.page)) {
    ctx.throw(404)
  }
  // 获取问题列表
  let getProblem = await u.http({
    url: u.queryQaList,
    params: {
      pageNum: ctx.params.page,
      pageSize,
      title: ctx.query.keyword || ''
    }
  })
  // 获取新闻资讯列表
  let getNews = await u.http({
    url: u.queryNewsList,
    params: {
      pageNum: 1,
      pageSize: 15,
      newsType: ''
    }
  })
  // 面包屑
  let crumbsData = [{
    name: '首页',
    href: '/'
  }, {
    name: '常见问题',
    href: ''
  }]
  
  await ctx.render('cjwt.ejs', {
    config: ctx.config,
    problemData: getProblem.code == 200 ? getProblem.data.list : [],
    problemDataTotal: getProblem.code == 200 ? getProblem.data.total : 0,
    problemDataPageNum: getProblem.code == 200 ? getProblem.data.pageNum : 0,
    problemDataPageSize: pageSize,
    searchValue: ctx.query.keyword || '',
    newsData: getNews.code == 200 ? getNews.data.list : [],
    crumbsData
  })
})

module.exports = router